<template>
  <a-card :bordered="false">
    <!-- 查询区域 -->
    <div class="table-page-search-wrapper">
      <a-form layout="inline" @keyup.enter.native="searchQuery">
        <a-row :gutter="24">
            <a-col :md="6" :sm="8">
                <a-form-item label="推荐获奖等级">
                    <a-select v-model="queryParam.jxdj" placeholder="请选择奖项等级" @change="handleSelectJxdj">
                        <a-select-option value="1">一等奖</a-select-option>
                        <a-select-option value="2">二等奖</a-select-option>
                      <!--
                        <a-select-option value="3">三等奖</a-select-option>
                        -->
                    </a-select>
                </a-form-item>
            </a-col>
            <!-- <a-col :md="6" :sm="8">
                <a-form-item label="分组名称">
                    <a-select v-model="queryParam.fzid" placeholder="请选择分组" @change="handleSelectFz">
                        <a-select-option v-for="item in fsfzlist" :key="item.id" :value="item.id">
                            {{item.wysd_fz_mc}}
                        </a-select-option>
                    </a-select>
                </a-form-item>
            </a-col> -->
            <a-col :sm="8">
                <a-form-item label="">
                    <!-- <a-button v-if="isTp" style="margin-right:10px;" type="primary" disabled>提交</a-button>
                    <template v-else>
                        <a-button v-if="userRole==3" style="margin-right:10px;" type="primary" @click="handleSubmit">提交</a-button>
                    </template> -->
                    <a-button v-if="userRole==3" style="margin-right:10px;" type="primary" @click="handleSubmit" :disabled="isTp?true:false">提交</a-button>
                  <!-- 隐藏签名按钮
                    <a-button type="primary" style="margin: 0px;" @click="submitQrode()" :disabled="disabledSig">签名</a-button>
                    <a-button type="primary" style="margin: 0px 0 0 10px;" :disabled="!isTp || !disabledSig" @click="ratingPreview(1)">投票预览</a-button>
                    -->
                </a-form-item>
            </a-col>
        </a-row>
      </a-form>
    </div>
    <!-- 查询区域-END -->

    <!-- table区域-begin -->
    <div>

      <a-table
        ref="table"
        size="middle"
        :scroll="{x:'auto'}"
        bordered
        rowKey="id"
        :columns="columns"
        :dataSource="dataSource"
        :pagination="ipagination"
        :loading="loading"
        :rowSelection="{selectedRowKeys: selectedRowKeys, onChange: onSelectChange}"
        class="j-table-force-nowrap"
        @change="handleTableChange">

        <template slot="htmlSlot" slot-scope="text">
          <div v-html="text"></div>
        </template>
        <template slot="imgSlot" slot-scope="text">
          <span v-if="!text" style="font-size: 12px;font-style: italic;">无图片</span>
          <img v-else :src="getImgView(text)" height="25px" alt="" style="max-width:80px;font-size: 12px;font-style: italic;"/>
        </template>
        <template slot="fileSlot" slot-scope="text">
          <span v-if="!text" style="font-size: 12px;font-style: italic;">无文件</span>
          <a-button
            v-else
            :ghost="true"
            type="primary"
            icon="download"
            size="small"
            @click="downloadFile(text)">
            下载
          </a-button>
        </template>
        <!-- <template slot="cgmc" slot-scope="text, record">
            <span>{{record.zg_xmmc}}<img class="pointer" style="margin-left: 10px;" @click="viewDetail(record)" src="@/assets/img/xszt.png"/></span>
        </template> -->
        <template slot="tpjg" slot-scope="text, record">
            <!-- 1-同意，2-不同意，0-弃权 -->
            <a-radio-group default-value="1" v-model="record.tp_jg">
                <a-radio value="1">同意</a-radio>
                <a-radio value="2">不同意</a-radio>
                <a-radio value="0">弃权</a-radio>
            </a-radio-group>
        </template>
      </a-table>
    </div>
    <!-- 二维码 -->
    <a-modal
        :visible="qrcodeVisible"
        @cancel="handleCancel()"
        title="请用手机扫二维码签名"
        centered
        :footer="null"
        width="400px"
        height="400px"
    >
        <vue-qr :text="imgQrUrl" :size="360" :margin="0"></vue-qr>
    </a-modal>
    <!-- pdf -->
    <view-pdf :params="pafParams" :showPdf="showpdf" @reset="getQrUrl" :pafBtn="pafBtn" path="cxjWysdTpZgcg"></view-pdf>
    <cxj-wysd-tp-modal ref="modalForm" @ok="modalFormOk"></cxj-wysd-tp-modal>
  </a-card>
</template>

<script>
import VueQr from 'vue-qr'
import viewPdf from '@/views/cxj/viewPdf'
  import '@/assets/less/TableExpand.less'
  import { mixinDevice } from '@/utils/mixin'
  import { JeecgListMixin } from '@/mixins/JeecgListMixin'
  import CxjWysdTpModal from './modules/CxjWysdTpModal'
import { filterObj } from '@/utils/util';
import Vue from 'vue'
import { USER_INFO, ACCESS_TOKEN } from "@/store/mutation-types"
import {
    cxjWysdTpZgcg,
    cxjzxpdSubmitStatusTpJs,
    cxjzxpdIsShowSig,
    cxjzxpdGetQrcodeTpJs
} from "@/api/api"
import {
    getAction,
} from "@/api/manage"
  export default {
    name: 'CxjWysdTpList',
    // mixins:[JeecgListMixin, mixinDevice],
    components: {
      CxjWysdTpModal,
      VueQr,
      viewPdf
    },
    data () {
      return {
        pdfFilePath: '',
        showpdf: false,
        pafBtn: false,
        pafParams: {},
        qrcodeVisible: false,
        signStatus: false,
        imgQrUrl: '',
        description: '委员审定投票表管理页面',
        disabledSig: true,
         /* 列表参数开始 */
        queryParam: {},
        dictOptions:{},
        superFieldList:[],
        fileStatus: "",
        selectedRowKeys: [],
        selectionRows: [],
        loading: false,
        isorter: {
            column: 'createTime',
            order: 'desc',
        },
        dataSource: [],
        ipagination: {
            current: 1,
            pageSize: 300,
            pageSizeOptions: ['10', '20', '300'],
            showTotal: (total, range) => {
            return range[0] + "-" + range[1] + " 共" + total + "条"
            },
            showQuickJumper: true,
            showSizeChanger: true,
            total: 0
        },
        /* 列表参数结束 */
        // 表头
        columns: [
          {
            title: '序号',
            dataIndex: '',
            key:'rowIndex',
            width:'5%',
            align:"center",
            customRender:function (t,r,index) {
              return parseInt(index)+1;
            }
          },
          {
            title:'成果编号',
            align:"center",
            width:'10%',
            dataIndex: 'zg_xmbh'
          },
          {
            title:'成果名称',
            align:"left",
            dataIndex: 'zg_xmmc',
            // scopedSlots: { customRender: 'cgmc' }
          },
          {
            title:'申报单位',
            align:"center",
            width:'15%',
            dataIndex: 'zg_sbdw'
          },
          {
            title:'推荐单位',
            align:"center",
            width:'12%',
            dataIndex: 'zg_tjdw'
          },
          {
            title:'成果类别',
            align:"center",
            width:'7%',
            // dataIndex: 'zg_xmlb'
            dataIndex: 'zg_xmlb'
          },
          {
            title:'推荐奖项',
            align:"center",
            width:'7%',
            dataIndex: 'xm_hjdj_show'
          },
          {
            title:'投票意见',
            align:"center",
            width:'20%',
            dataIndex: 'tp_jg',
            scopedSlots: { customRender: 'tpjg' }
          },
         /*  {
            title: '操作',
            dataIndex: 'action',
            align:"center",
            fixed:"right",
            width:147,
            scopedSlots: { customRender: 'action' }
          } */
        ],
        url: {
          list: "/cxj/cxjWysdTpZgcg/cxjwysd_tpxmListZj",
          delete: "/cxj/cxjWysdTp/delete",
          deleteBatch: "/cxj/cxjWysdTp/deleteBatch",
          exportXlsUrl: "/cxj/cxjWysdTp/exportXls",
          importExcelUrl: "cxj/cxjWysdTp/importExcel",
          cxjwysdFzlist: '/cxj/cxjWysdFzZgcg/cxjwysd_fzlist'
        },
        dictOptions:{},
        superFieldList:[],

        fsfzlist: [],
        isTp: false,
        userRole: sessionStorage.getItem('role')
      }
    },
    created() {
        this.getSuperFieldList();
        this.queryParam.jxdj = "1";
        this.loadData();
        // this.getcxjwysdFzlist();
    },
    computed: {
      importExcelUrl: function(){
        return `${window._CONFIG['domianURL']}/${this.url.importExcelUrl}`;
      },
    },
    methods: {
      handleCancel() {
            clearInterval(this.qrTimer)
            this.qrcodeVisible = false;
        },
        // 评分预览
        ratingPreview(flag) {
            this.pafBtn = flag == 1 ? false : true
            this.pafParams = {
                fzid: 111
            }
            this.showpdf = !this.showpdf
        },
        // 查询签名状态
        checkSignStatus(params) {
            clearInterval(this.qrTimer)
            this.qrTimer = setInterval(() => {
                cxjzxpdSubmitStatusTpJs(params,'cxjWysdTpZgcg').then(res=>{
                    if (res.result) {
                        clearInterval(this.qrTimer)
                        this.qrcodeVisible = false
                        this.ratingPreview(1)
                        this.signStatus = true
                        this.$message.success("签名成功！")
                        this.isShowSigFun()
                    }
                }).catch(err => {
                    this.$message.error("查询签名状态失败！")
                })
            }, 1000)
        },
        submitQrode() {
            this.getQrUrl()
        },
        // 查询二维码地址
        getQrUrl() {
            let formData = new FormData();
            cxjzxpdGetQrcodeTpJs(formData,'cxjWysdTpZgcg').then(res=>{
                if (res.code === 200) {
                    this.imgQrUrl = `${window.location.origin}${res.result}&path=cxjWysdTpZgcg`
                    this.qrcodeVisible = true
                    this.checkSignStatus({
                        fzid: 1
                    })
                } else {
                    this.$message.error(res.message)
                }
            }).catch(err => {
                this.$message.error('查询二维码失败')
            })
        },
        // 查看成果详情
        viewDetail(item){
            // console.log('成果推荐管理',item)
            let token = Vue.ls.get(ACCESS_TOKEN);
            sessionStorage.setItem('token', token);
             let routeData = this.$router.resolve({
                path: '/shenbao/declare',
                query: {
                    type: '11',
                    cxj_cxj_id: item.id,
                    isHead: 2,
                    from: 'zj',
                    cxj_xmbh: item.cxj_xmbh,
                    cxj_mc_zw: item.cxj_mc_zw
                }
            });
            window.open(routeData.href, '_blank');
        },
        handleSubmit: function () {
            var jgarr = [];
            let self = this;
            this.$confirm({
                title: '提交后不可修改，是否提交？',
                onOk() {
                    self.dataSource.forEach(element => {
                        jgarr.push(element.tp_jg)
                    });
                    // console.log('asdfasdfasdfasd',jgarr)
                    cxjWysdTpZgcg({
                        tpjgs: jgarr.join(','),
                        fzid: self.queryParam.fzid,
                        jxdj: self.queryParam.jxdj
                    }).then(res=>{
                        if (res.code=='200') {
                            self.$message.success(res.result);
                            self.loadData();
                        } else {
                            self.$message.error('提交失败');
                        }
                    })
                },
                onCancel() {},
            });
        },
        getcxjwysdFzlist(){
            getAction(this.url.cxjwysdFzlist).then((res) => {
              if (res.success) {
                  this.fsfzlist = res.result.records || res.result;
                  this.queryParam.fzid = this.fsfzlist[0].id;
                  this.loadData();
              }
          })
        },
        handleSelectJxdj(value){
            this.queryParam.jxdj = value;
            this.loadData();
        },
       /*  handleSelectFz(value){
            this.queryParam.fzid = value;
            this.loadData();
        }, */
        /* 获取列表固定格式开始 */
        getQueryField() {
            //TODO 字段权限控制
            var str = "id,";
            this.columns.forEach(function (value) {
                str += "," + value.dataIndex;
            });
            return str;
        },
        // 获取分组项目
        loadData(arg) {
            if (!this.url.list) {
                this.$message.error("请设置url.list属性!")
                return
            }
            //加载数据 若传入参数1则加载第一页的内容
            if (arg === 1) {
                this.ipagination.current = 1;
            }
            var params = this.getQueryParams();//查询条件
            this.loading = true;
            // cxjzxpdSubmitStatusTpJs(params,'cxjWysdTpZgcg').then(res=>{
            //     if (res.result) {
            //         this.signStatus = true
            //     } else {
            //         this.signStatus = false
            //     }
            // }).catch(err => {
            //     this.$message.error("查询签名状态失败！")
            // })
            this.isShowSigFun()
            // 分组id
            getAction(this.url.list, params).then((res) => {
                if (res.success) {
                    //update-begin---author:zhangyafei    Date:20201118  for：适配不分页的数据列表------------
                    this.dataSource = res.result.tpxmList || res.result;
                    this.isTp = res.result.isTp;
                    this.dataSource.map(item=>{
                        // item.tp_jg = "1"
                        if (!item.tp_jg){
                            item.tp_jg = "1"
                        }
                    })
                    if (res.result.total) {
                        this.ipagination.total = res.result.total;
                    } else {
                        this.ipagination.total = 0;
                    }
                    //update-end---author:zhangyafei    Date:20201118  for：适配不分页的数据列表------------
                }
                if (res.code === 510) {
                    this.$message.warning(res.message)
                }
                this.loading = false;
            })
        },
      isShowSigFun(){
        cxjzxpdIsShowSig(this.params,'cxjWysdTpZgcg').then(res=>{
          if (res.result) {
            this.disabledSig = false
          } else {
            this.disabledSig = true
          }
        }).catch(err => {
          this.$message.error("查询签名状态失败！")
        })
      },
        onSelectChange(selectedRowKeys, selectionRows) {
            this.selectedRowKeys = selectedRowKeys;
            this.selectionRows = selectionRows;
        },
        onClearSelected() {
            this.selectedRowKeys = [];
            this.selectionRows = [];
        },
        modalFormOk() {
            // 新增/修改 成功时，重载列表
            this.loadData();
            //清空列表选中
            this.onClearSelected()
        },
        handleTableChange(pagination, filters, sorter) {
            //分页、排序、筛选变化时触发
            //TODO 筛选
            if (Object.keys(sorter).length > 0) {
                this.isorter.column = sorter.field;
                this.isorter.order = "ascend" == sorter.order ? "asc" : "desc"
            }
            this.ipagination = pagination;
            this.loadData();
        },

        getQueryParams() {
            //获取查询条件
            let sqp = {}
            if (this.superQueryParams) {
                sqp['superQueryParams'] = encodeURI(this.superQueryParams)
                sqp['superQueryMatchType'] = this.superQueryMatchType
            }
            this.queryParam.shijian = this.shijian;
            var param = Object.assign(sqp, this.queryParam, this.isorter, this.filters);
            param.field = this.getQueryField();
            param.pageNo = this.ipagination.current;
            param.pageSize = this.ipagination.pageSize;
            return filterObj(param);
        },
        searchQuery() {
            this.loadData(1);
        },
        searchReset() {
            this.queryParam = {};
            // this.flid = "";
            this.shijian = moment(new Date()).format('YYYY');
            this.queryParam.shijian = this.shijian;
            this.loadData(1);
        },
        /* 获取列表固定格式结束 */
      initDictConfig(){
      },
      getSuperFieldList(){
        let fieldList=[];
        fieldList.push({type:'string',value:'cxjCxjId',text:'成果ID',dictCode:''})
        fieldList.push({type:'string',value:'sysZjId',text:'专家ID',dictCode:''})
        fieldList.push({type:'string',value:'xmHjdj',text:'获奖等级',dictCode:''})
        fieldList.push({type:'string',value:'xmHjdjShow',text:'显示获奖等级',dictCode:''})
        fieldList.push({type:'string',value:'tpJg',text:'投票结果',dictCode:''})
        fieldList.push({type:'string',value:'tpZt',text:'投票状态',dictCode:''})
        fieldList.push({type:'string',value:'isValid',text:'是否有效',dictCode:''})
        fieldList.push({type:'string',value:'shijian',text:'时间',dictCode:''})
        this.superFieldList = fieldList
      }
    }
  }
</script>
<style scoped>
  @import '~@assets/less/common.less';
  /deep/.ant-table-tbody > tr > td {
    word-break: break-all;
    white-space: normal;
    word-wrap:break-word;
    font-size:14px;
    padding:3px 3px!important;
  }
</style>